<?php
if (!defined("_INDEX")) { header("Location: /"); die;}


// редиректит на страницу
function goToPage($url='/'){
	header("Location: $url");
	exit;
}

// подгружает страницу
function loadPage($page='head.php',$params=null,$counter=0,$path=""){
	
	global $route;
	global $db;
	global $user;
	global $current_admin_city;
	global $this_city;
	global $this_city_inf;
	global $head_title;
	global $head_keywords;
	global $head_description;
	
	if ($counter < 3)
	{
		// если вызвали первый раз узнаем путь в котором работаем
		if ($path == "")
		{
			$trace = debug_backtrace();
			$path = dirname($trace[0]['file']);
		}
		// если не нашли путь ищем выше
		if (!is_file($path.DS.$page))
			loadPage($page,$params,++$counter,dirname($path));
		else // нашли - подключаем
		{
			if ($params){
				foreach ($params as $key => $param){
					$$key = $param;
				}
			}

			require $path.DS.$page;
		}
	}
	else
		die("not found");
}

// Функция обрезает $text до последнего слова из $limit символов
function crop_text($text,$limit=500)
{
	if (strlen($text) > $limit)
	{
		$text = mb_substr($text,0,$limit,"utf8");
		
		for ($i = strlen($text)-1; $i>0; $i--)
		{
			if (preg_match("/\s/",mb_substr($text,$i,1,"utf8")))
				if (preg_match("/[a-zA-Zа-яА-Я«»\.,]/",mb_substr($text,$i-1,1,"utf8")))
					break;
		}
		$text = mb_substr($text,0,$i,"utf8")." ...";
	}
	
	return $text;
}

// вставляет $insert в $text после первого абзаца
function print_news($text,$insert=""){
	if ($pos = mb_strpos($text,"<br />"))
		$text = substr_replace($text,"</p><p class='insert'>".$insert."</p><p class='news_text'>",$pos,6);
	else
		$text .= $insert;
	
	return $text;
}

// создает список select
function select_create($array,$key,$value,$compare="")
{
	$select = "";
	
	foreach ($array as $k=>$val)
	{
		if ($compare != "" && $compare == $val[$key])
			$select .= "<option selected value='".$val[$key]."'>".$val[$value]."</option>";
		else
			$select .= "<option  value='".$val[$key]."'>".$val[$value]."</option>";
	}
	
	return $select;
}

// function randString - generate random string of $len symbols from $alphabet
function randString($len=8,$alphabet="Hsz5Q0@a_Jp1*78FAEWufwkLhGgbVCxZ"){
	$str = "";
	
	for ($i = 0; $i < $len; $i++)
	{
		$symbol_num = rand(0,strlen($alphabet)-1);
		$str .= $alphabet[$symbol_num];
	}
	
	return $str;
}

// переводит url в транслит
function translitIt($str) 
{
	$tr = array(
		"А"=>"A","Б"=>"B","В"=>"V","Г"=>"G",
		"Д"=>"D","Е"=>"E","Ж"=>"J","З"=>"Z","И"=>"I",
		"Й"=>"Y","К"=>"K","Л"=>"L","М"=>"M","Н"=>"N",
		"О"=>"O","П"=>"P","Р"=>"R","С"=>"S","Т"=>"T",
		"У"=>"U","Ф"=>"f","Х"=>"h","Ц"=>"ts","Ч"=>"ch",
		"Ш"=>"Sh","Щ"=>"Sch","Ъ"=>"","Ы"=>"Yi","Ь"=>"",
		"Э"=>"E","Ю"=>"Yu","Я"=>"Ya","а"=>"a","б"=>"b",
		"в"=>"v","г"=>"g","д"=>"d","е"=>"e","ж"=>"j",
		"з"=>"z","и"=>"i","й"=>"y","к"=>"k","л"=>"l",
		"м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r",
		"с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h",
		"ц"=>"ts","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"y",
		"ы"=>"yi","ь"=>"","э"=>"e","ю"=>"yu","я"=>"ya", 
		" "=> "-", "."=> "", ","=> "", "/"=> "_", "\""=> "", "'"=> "", ":"=> "", ";"=> "",
		"["=> "", "]"=> "", "("=> "", ")"=> "", "{"=> "", "}"=> "", "«"=> "", "»"=> "",
		"`"=> "", "~"=> "", "!"=> "", "@"=> "", "#"=> "", "$"=> "", "%"=> "", "^"=> "", "&"=> "", "*"=> "", "="=> "", "["=> "", "\\"=> "", "|"=> "", "/"=> "", "<"=> "", ">"=> "", "?"=> ""
	);
	return strtr($str,$tr);
}

// function wordEnding - returns word $ending depending on $count $with or without $count
function wordEnding($count,$ending1,$ending2,$ending3,$with=true,$one=true)
{
	if ($count == 1)
		return $one ? $ending1 : "1 $ending1";
	$count = (string)$count;
	$char = (int)$count[strlen($count)-1];
	if ($char == 1)
		$word = $ending1;
	elseif ($char > 1 && $char < 5)
		$word = $ending2;
	elseif ($char >= 5 || $char == 0)
		$word = $ending3;
	
	// если число больше 10
	if (((int)$count)/10 > 1)
	{
		// работаем со строкой, т.к. $count может быть, например 112
		$char = (int)($count[strlen($count)-2].$count[strlen($count)-1]);
		if ($char > 10 && $char < 15)
			$word = $ending3;
	}
	
	return $with ? $count." ".$word : $word;	
}

function createCLink($city,$company){
	return "http://".$city.".".DOMAIN."/company/".$company;
}

function makeSpaces($number)
{
	$number = (string)$number;
	$length = strlen($number);
	
	$count = (int)($length / 3);
	if ($count > 0)
	{
		$new_num = "";
		$i = 0;
		$str = strrev($number);
		while ($i < $count)
			$new_num .= substr($str,($i++)*3,3)." ";
		$new_num .= substr($str,$count*3,$length - $count*3);
		
		return strrev(trim($new_num));
	}
	return $number;
}

function showPages($count, $limit)
{
	global $route;
	if ($count > $limit)
	{
		$max_page = ceil($count/$limit); // всего страниц может быть
		$page = UV::readInt(strip_tags($route->GET("page")));
		$page = $page < 1 ? 1 : ($page > $max_page ? $max_page : $page);
		
		$url_query = array();
		$url_arr = parse_url($_SERVER['REQUEST_URI']);
		if (isset($url_arr['query']))
			$url_query = explode("&",$url_arr['query']);
		
		$new_url = $prev_url = $next_url = "?";
		$tmp_arr = array();
		
		// находим page=x или пустые строки и стираем
		for ($z=0; $z<count($url_query); $z++)
			if ((strpos($url_query[$z],"page=") === false) && ($url_query[$z] != ""))
				$tmp_arr[] = $url_query[$z];
		$url_query = $tmp_arr;
		
		// записываем строку обратно
		for ($q=0; $q<count($url_query); $q++)
		{
			$new_url .= $url_query[$q];
			if ($q < count($url_query)-1)
				$new_url .= "&";
		}
		$next_url = $prev_url = $new_url;
		
		if (count($url_query) > 0)
			$next_url = $prev_url .= "&";
		// дописываем страницы
		if ($route->GET('page'))
		{
			$prev_url .= "page=".($page-1);
			$next_url .= "page=".($page+1);
		}
		else
			$next_url .= "page=2";
			
		$next = "";
		$prev = "";
		
		if ($page < $max_page)
			$next = "<a class='page_active' href='".$next_url."'>Следующая &rarr;</a>";
		else
			$next = "<span class='page_inactive'>Следующая &rarr;</span>";
		
		if ($page > 1)
			$prev = "<a class='page_active' href='".$prev_url."'>&larr; Предыдущая</a>";
		else
			$prev = "<span class='page_inactive'>&larr; Предыдущая</span>";

		$str = "<div class='pages_title'>Страницы</div>";
		$str .= "$prev &nbsp;&nbsp;&nbsp;&nbsp; $next";
		$str .= "<div class='pages'>";
		for ($x = 1; $x <= $max_page; $x++)
		{
			if ($x == $page){
				$str .= "<span class='page_item'>$x</span> ";
			} else {
				$str .= "<a class='page_active page_item' href='".$new_url;
				if (count($url_query) > 0)
					$str .= "&";
				$str .= "page=".$x."'>".$x."</a> ";
			}
		}
		$str .= "</div>";
		
		return $str;
	}
}

?>